package com.lyf.boot.core.model;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Luyufan
 * @date 2023/7/7 9:29
 */
@Data
@Accessors(chain = true)
public class PageInfo<T> {

    /**
     * 总条数
     */
    private Long total;

    /**
     * 总页数
     */
    private Long pages;

    /**
     * 数据列表
     */
    private List<T> records;

    public static <T> PageInfo<T> build(Page<T> page){
        return new PageInfo<T>().setTotal(page.getTotal())
                .setPages(page.getPages())
                .setRecords(page.getRecords());
    }

    public static <T> PageInfo<T> build(List<T> list, int pageNum, int pageSize){
        int total = list.size();
        int pages = PageUtil.totalPage(total, pageSize);
        List<T> records = new ArrayList<>();
        if(pageNum <= pages){
            int end = pageNum * pageSize;
            end = Math.min(end, total);
            records = CollUtil.sub(list,(pageNum - 1) * pageSize, end);
        }
        return new PageInfo<T>().setTotal((long)total)
                .setRecords(records)
                .setPages((long)pages);
    }

    @JsonIgnore
    public boolean isEmpty(){
        return CollUtil.isEmpty(records);
    }

}
